﻿namespace Mongo.Controllers
{
    #region

    using System.Linq;
    using System.Web.Mvc;
    using Core.Interfaces;
    using Core.Repository;
    using MongoDB.Bson;
    using ViewModels;

    #endregion

    public class UserController : Controller
    {
        private readonly IUserRepository _userRepository = new UserRepository();

        //
        // GET: /User/
        public ActionResult Index()
        {
            return View(_userRepository.All.ToList());
        }

        //
        // GET: /User/Details/5
        public ActionResult Details(string id)
        {
            var objectId = new ObjectId(id);
            return View(new UserViewModel(_userRepository.All.FirstOrDefault(u => u.Id == objectId)));
        }

        //
        // GET: /User/Create
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /User/Create
        [HttpPost]
        public ActionResult Create(UserViewModel user)
        {
            try
            {
                _userRepository.Insert(user.CopyTo());

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /User/Edit/5
        public ActionResult Edit(string id)
        {
            var objectId = new ObjectId(id);
            return View(new UserViewModel(_userRepository.All.FirstOrDefault(u => u.Id == objectId)));
        }

        //
        // POST: /User/Edit/5
        [HttpPost]
        public ActionResult Edit(UserViewModel user)
        {
            try
            {
                _userRepository.Update(user.CopyTo());

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /User/Delete/5
        public ActionResult Delete(string id)
        {
            var objectId = new ObjectId(id);
            return View(new UserViewModel(_userRepository.All.FirstOrDefault(u => u.Id == objectId)));
        }

        //
        // POST: /User/Delete/5
        [HttpPost]
        public ActionResult Delete(string id, FormCollection collection)
        {
            try
            {
                ObjectId objectId = new ObjectId(id);
                _userRepository.Remove(objectId);

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
